package com.derbysoft.lowcostadapter.commons.redis.service.impl;

import com.derbysoft.lowcostadapter.commons.model.ProviderIdentification;
import com.derbysoft.lowcostadapter.commons.redis.service.ProviderIdentificationCacheService;
import com.derbysoft.lowcostadapter.commons.redis.utils.KeyValueHelper;
import com.derbysoft.redis.clients.normal.SingleJedis;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * User: jason
 * Date: 2012-11-15
 */
@Service("providerIdentificationCacheService")
public class ProviderIdentificationCacheServiceImpl implements ProviderIdentificationCacheService {
    @Autowired
    private SingleJedis systemConfigRedis;

    @Override
    public ProviderIdentification get(String channelCode) {
        return getByKey(ProviderIdentification.PREFIX + StringUtils.upperCase(channelCode));
    }

    @Override
    public List<ProviderIdentification> loadAll() {
        List<ProviderIdentification> identifications = new ArrayList<ProviderIdentification>();
        for (String key : systemConfigRedis.keys(ProviderIdentification.PREFIX + "*")) {
            ProviderIdentification identification = getByKey(key);
            if (identification != null) {
                identifications.add(identification);
            }
        }
        return identifications;
    }

    @Override
    public void saveAll(List<ProviderIdentification> identifications) {
        for (ProviderIdentification identification : identifications) {
            systemConfigRedis.set(identification.toKey(), identification.toValue());
        }
    }

    private ProviderIdentification getByKey(String key) {
        String value = systemConfigRedis.get(key);
        if (value == null) {
            return null;
        }
        String[] fields = StringUtils.split(value, KeyValueHelper.SEPARATOR);
        ProviderIdentification providerIdentification = new ProviderIdentification();
        providerIdentification.setChannelCode(StringUtils.split(key, KeyValueHelper.SEPARATOR)[1]);
        providerIdentification.setUserName(fields[0]);
        providerIdentification.setPassWd(fields[1]);
        providerIdentification.setAgentReference(fields[2]);
        return providerIdentification;
    }
}
